package com.lzcsjk;

import com.google.gson.Gson;
import com.lzc.DBUtil;
import model.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.*;
import java.util.ArrayList;

//@WebServlet("/product_list.do")
public class ProductListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest reg, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取数据库连接
        Connection conn = DBUtil.getConnection();
        //2、准备SQL
        String sql = "select * from tb_product order by create_time desc limit 10";
        //3、声明操作对象
        PreparedStatement ps = null;
        //4、声明结果集对象
        ResultSet rs = null;
        try {
//5、获取操作对象
            ps = conn.prepareStatement(sql);
//6、执行SQL并返回结果集
            rs = ps.executeQuery();
            //使用List来存储商品信息
            ArrayList list = new ArrayList();
//7、解析结果集
            while (rs.next()) {
                //创建结果集
                Product product = new Product();
                product.setDescription(rs.getString("description"));
                product.setName(rs.getString("name"));
                product.setId(rs.getInt("id"));
                product.setMarket_price(rs.getDouble("market_price"));
                product.setSell_price(rs.getDouble("sell_price"));
                product.setCategory_main_id(rs.getInt("category_main_id"));
                product.setCategory_branch_id(rs.getInt("category_branch_id"));
                product.setPicture(rs.getString("picture"));

//将商品信息添加到list中
                list.add(product);
//将对象置为空，让GC尽快回收相关的内存
                product = null;
            }
            //9.将List对象转为JSON格式字符串
            Gson gson = new Gson();
            String result = gson.toJson(list);
            //10、获取输出流
//10.1、设置响应的内容类型
            resp.setContentType("application/json");
//10.2、设置响应的数据编码格式
            resp.setCharacterEncoding("utf-8");
//10.3、输出响应数据
            resp.getWriter().print(result);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
//8、关闭资源

        DBUtil.closeResource(conn, ps, rs);

    }

}